package com.cubix.persistence.jpa;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;

import com.cubix.persistence.util.JPAUtil;

public abstract class GenericoJPA<T> implements Serializable
{

    private static final long serialVersionUID = 1L;
    protected EntityManager em;

    private Class<T> entityClass;

    public GenericoJPA(Class<T> entityClass)
    {
        this.entityClass = entityClass;
    }

    public void createEM()
    {
        em = JPAUtil.getEmf().createEntityManager();
    }

    public void releaseEM()
    {
        em.close();
    }

    public void beginTransaction()
    {
        em.getTransaction().begin();
    }

    public void endTransaction()
    {
        em.getTransaction().commit();
        releaseEM();
    }

    public void rollbackTransaction()
    {
        em.getTransaction().rollback();
        releaseEM();
    }

    public void flush()
    {
        em.flush();
    }

    public T find(Object id)
    {
        return em.find(entityClass, id);
    }

    public void change(T entity)
    {
        em.merge(entity);
    }

    public void remove(T entity)
    {
        em.remove(entity);
    }

    public void create(T entity)
    {
        em.persist(entity);
    }

    public List<T> findAllProductos()
    {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder()
                .createQuery();
        cq.select(cq.from(entityClass));
        return em.createQuery(cq).getResultList();
    }
}